<template>
  <div class="ptz-block" :style="cameraData.flvUrl == ''  ? 'color: #d8d9da' : 'cursor: pointer;'">
    <el-progress class="mic-level-bar" :percentage="level" :text-inside="true" v-if="ws"></el-progress>
    <div class="ptz-cell ptz-up" @mousedown="ptzControl('up')" @mouseup="ptzControl('stop')" command="up"
         title="上">
      <el-icon>
        <ArrowUpBold/>
      </el-icon>
    </div>
    <!--    <div class="ptz-cell ptz-upright" @mousedown="ptzControl('upright')" @mouseup="ptzControl('stop')"-->
    <!--         command="upright" title="左上">-->
    <!--      <el-icon>-->
    <!--        <ArrowUpBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <!--    <div class="ptz-cell ptz-upleft" @mousedown="ptzControl('upright')" @mouseup="ptzControl('stop')"-->
    <!--         command="upleft" title="右上">-->
    <!--      <el-icon>-->
    <!--        <ArrowUpBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <div class="ptz-cell ptz-left" @mousedown="ptzControl('left')" @mouseup="ptzControl('stop')"
         command="left" title="左">
      <el-icon>
        <ArrowLeftBold/>
      </el-icon>
    </div>
    <div class="ptz-center"
         :style="cameraData.flvUrl == '' || cameraData.flvUrl != 'ball' ? 'background-color: #d8d9da' : ''"
         title="长按通话，松开挂断">
      <!--      <el-icon @mousedown.prevent="talkStart" @mouseup.prevent="talkStop()">-->
      <!--        <Microphone :color="ws ? '#51f32d':'#968c8c'"/>-->
      <!--      </el-icon>-->

      <el-icon @mousedown.prevent="clickStartVoiceTalk()" @mouseup.prevent="clickStopVoiceTalk()"
               @mouseleave="">
        <Microphone :color="control ? '#51f32d':'#968c8c'"/>
      </el-icon>
    </div>
    <div class="ptz-cell ptz-right" @mousedown="ptzControl('right')" @mouseup="ptzControl('stop')"
         command="right" title="右">
      <el-icon>
        <ArrowRightBold/>
      </el-icon>
    </div>
    <!--    <div class="ptz-cell ptz-downleft" @mousedown="ptzControl('downleft')" @mouseup="ptzControl('stop')"-->
    <!--         command="downleft" title="右下">-->
    <!--      <el-icon>-->
    <!--        <ArrowDownBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <!--    <div class="ptz-cell ptz-downright" @mousedown="ptzControl('downright')" @mouseup="ptzControl('stop')"-->
    <!--         command="downright" title="左下">-->
    <!--      <el-icon>-->
    <!--        <ArrowDownBold/>-->
    <!--      </el-icon>-->
    <!--    </div>-->
    <div class="ptz-cell ptz-down" @mousedown="ptzControl('down')" @mouseup="ptzControl('stop')"
         command="down" title="下">
      <el-icon>
        <ArrowDownBold/>
      </el-icon>
    </div>
    <div class="ptz-cell-f ptz-zoobox">
      <div @mousedown="ptzControl('zoomin')" @mouseup="ptzControl('stop')" command="zoomin" title="放大">
        <el-icon>
          <Plus/>
        </el-icon>
      </div>
      <div @mousedown="ptzControl('zoomout')" @mouseup="ptzControl('stop')" command="zoomout" title="缩小">
        <el-icon>
          <Minus/>
        </el-icon>
      </div>
    </div>
  </div>
  <div style="display: flex;justify-content: space-around;padding-top: 154px">
    <el-button @click="singledefensesetup(true)">&nbsp;&nbsp;布防&nbsp;&nbsp;</el-button>
    <el-button @click="singledefensesetup(false)">&nbsp;撤防&nbsp;</el-button>
  </div>
  <div style="display: flex;justify-content: space-around;margin-top: 10px">
    <el-button @click="defensesetup(true)">一键布防</el-button>
    <el-button @click="defensesetup(false)">一键撤防</el-button>
  </div>
  <div style="display: flex;justify-content: space-around;margin-top: 20px">
    <el-button @click="collecthandle()">收藏</el-button>
  </div>


  <el-dialog v-model="collectdialog" title="收藏设置" width="25%">
    <Collects v-if="collectdialog" ref="collects" @close="collectdialog = false"></Collects>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="collectdialog = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="enterok()">{{ $t("confirm") }}</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script>
import {ElMessage} from "element-plus";
import baseService from "@/service/baseService";
import Collects from "@/views/livegbs/collects.vue";

export default {
  components: {Collects},
  props: ['playerList', 'iWndType', 'audioData'],
  data() {
    return {
      cameraData: {
        flvUrl: "",
        cameraType: ""
      },
      collectdialog: false,
      recorder: null,
      ws: null,
      level: 0,
      // 记录存储已登录音频ip
      ydlAudio: new Map(),
      control: false
    }
  },
  watch: {
    $route(to) {
      // 在这里编写处理路由变化的代码
    }
  },
  mounted() {
  },
  methods: {
    // 确定收藏
    enterok() {
      this.$refs.collects.dataForm.cameraList = [];
      this.$refs.collects.dataForm.winType = this.iWndType;
      this.playerList.forEach((i) => {
        this.$refs.collects.dataForm.cameraList.push({
          cameraId: i.id,
          idIndex: i.idIndex
        })
      });
      this.$refs.collects.enterok().then((result) => {
        this.$emit("liveNewreRresh");
      })
    },
    collecthandle() {
      this.collectdialog = true;
    },
    // 控制
    ptzControl(command) {
      if (this.cameraData.flvUrl === "") {
        return;
      }
      let pamers = {
        serial: this.cameraData.gbsCode,
        command: command
      }
      $.ajax({
        method: "GET", // type: "GET", is also ok, method since jquery 1.9
        url: `${this.$store.state.apiUrl}/api/v1/control/ptz?token=${this.$store.state.accessToken}`,
        global: false,
        data: pamers
      }).done(() => {
        this.$emit("liveNewData", this.cameraData, 0)
      }).fail(xhr => {
        if (xhr) {
        }
      })
    },
    // 单独 撤防 布防
    singledefensesetup(defen) {
      let id = this.cameraData.id;
      if (id === undefined) {
        ElMessage.error(" 该窗口暂无设备播放，请先选择设备！");
        return;
      }
      if (this.cameraData.type.includes("mn")) {
        ElMessage.warning(" 模拟相机不支持撤布防！");
        return;
      }
      if (defen) {
        baseService.post("Camera/kxcamera/setAlarmByIds", [id]).then(() => {
          ElMessage.success("布防成功！");
          this.$emit("defenhandle");
        });
      } else {
        baseService.post("Camera/kxcamera/outAlarmByIds", [id]).then(() => {
          ElMessage.success("撤防成功！");
          this.$emit("defenhandle");
        });
      }
    },
    // 集体 撤防 布防
    defensesetup(defen) {
      let id = this.cameraData.id;
      if (id === undefined) {
        ElMessage.error(" 该窗口暂无设备播放，请先选择设备！");
        return;
      }
      if (this.cameraData.type.includes("mn")) {
        ElMessage.warning(" 模拟相机不支持撤布防！");
        return;
      }
      if (defen) {
        baseService.post("Camera/kxcamera/setAlarmById?id=" + id).then(() => {
          ElMessage.success("布防成功！");
          this.$emit("defenhandle");
        });
      } else {
        baseService.post("Camera/kxcamera/outAlarmById?id=" + id).then(() => {
          ElMessage.success("撤防成功！");
          this.$emit("defenhandle");
        });
      }
    },
    openvocality() {
      this.$emit("openvocality", this.cameraData.idIndex)
    },
    closevocality() {
      this.$emit("closevocality", this.cameraData.idIndex)
    },
    wsTalkURL() {
      console.log(this.cameraData)
      return
      this.$emit("liveNewData", this.cameraData, 60)
      var player = this.cameraData;
      let url = ""
      console.log(player)
      if (!player || !player.gbsCode || !player.gbsCode) return '';
      var protocol = "ws:";
      if (this.$store.state.apiUrl.startsWith("https")) {
        url = this.$store.state.apiUrl.replace("https:", "");
        protocol = "wss:";
      } else {
        url = this.$store.state.apiUrl.replace("http:", "");
        protocol = "ws:";
      }
      return `${protocol}${url}/api/v1/control/ws-talk/${player.gbsCode}/${player.gbsCode}?format=pcm&token=${this.$store.state.accessToken}`;

      // return "wss://192.168.0.9:10010/api/v1/control/ws-talk/51010001421327000054/51010001421327000054?format=pcm"
    },
    talkStart(e) {
      if (!this.ws) {
        var talkURL = this.wsTalkURL();
        console.log(talkURL)
        if (!talkURL) return;
        this.ws = new WebSocket(talkURL);
        this.ws.onopen = evt => {
          console.log("ws talk open");
          ElMessage.success("对话通道连接成功！");
        }
        this.ws.onclose = evt => {
          console.log("ws talk close");
        }
        this.ws.onerror = evt => {
          console.log("ws talk error", evt);
          ElMessage.error("对话通道连接失败！");
        }
      } else {
        this.talkStop();
        return;
      }
      var $target = $(e.currentTarget);
      if (this.recorder) {
        $target.addClass("active");
        this.recorder.start();
        return;
      }
      LiveRecorder.get((rec, err) => {
        if (err) {
          alert(err);
          this.talkStop();
          return
        }

        // this.$refs["player"].setMuted(true);
        this.openvocality();
        $target.addClass("active");
        this.recorder = rec;
        this.recorder.start();
      }, {
        sampleBits: 16,
        sampleRate: 8000,
        pcmCallback: (pcm, level) => {
          // binary to base64 string
          var reader = new window.FileReader();
          reader.onloadend = () => {
            var base64 = reader.result;
            var base64 = base64.split(',')[1];
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
              this.ws.send(base64);
              this.level = level;
            }
          }
          reader.readAsDataURL(pcm);
        }
      })
    },
    talkStop() {
      if (this.recorder) {
        // this.recorder.stop();
        this.recorder.destroy();
        this.recorder = null;
        $(this.$el).find(".fa-microphone.active").removeClass("active");
        // this.$refs["player"].setMuted(false);
        // this.closevocality();
      }
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
      this.level = 0;
    }
  }
}
</script>


<style scoped lang="scss">
.mic-level-bar {
  position: absolute;
  transform: rotate(-90deg);
  width: 100%;
  top: 70px;
  left: -80px;
}

.ptz-block {
  width: 100%;
  position: relative;
  font-size: 24px;

  .ptz-cell {
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
  }

  .ptz-cell-f {
    width: 50px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;

    div:hover {
      color: #51f32d;
    }
  }

  .ptz-cell.active {
    color: #ccc;
    font-size: 26px;
  }

  .ptz-cell.readonly {
    color: #ddd;
  }

  .ptz-cell:hover {
    color: #51f32d;
  }

  .fa-microphone, .fa-microphone-slash {
    padding: 10px 13px;
    border-radius: 25px;
  }

  .fa-microphone.active {
    color: #FFF;
  }

  .fa-microphone.readonly {
    color: #ddd;
  }

  .fa-microphone-slash.readonly {
    color: #ddd;
  }

  .mic-level-bar {
    position: absolute;
    transform: rotate(-90deg);
    width: 70%;
    top: 80px;
    left: -50px;
  }

  .ptz-center {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 40px;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 50%;
    background-color: #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .ptz-up {
    top: 0;
    left: 50%;
    transform: translateX(-50%);
  }

  .ptz-upright {
    top: 15px;
    left: 55%;
    transform: rotate(45deg);
  }

  .ptz-upleft {
    top: 15px;
    left: 22%;
    transform: rotate(-45deg);
  }

  .ptz-left {
    top: 40px;
    left: 32%;
    transform: translateX(-50%);
  }

  .ptz-right {
    top: 40px;
    left: 68%;
    transform: translateX(-50%);
  }

  .ptz-downleft {
    top: 85px;
    left: 22%;
    transform: rotate(45deg);
  }

  .ptz-downright {
    top: 85px;
    left: 55%;
    transform: rotate(-45deg);
  }

  .ptz-down {
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
  }

  .ptz-zoobox {
    width: 40%;
    top: 110px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: space-between;
  }


  //.ptz-up,
  //.ptz-left,
  //.ptz-right,
  //.ptz-down,
  //.ptz-center > .fa-microphone,
  //.ptz-zoomin,
  //.ptz-talk > .fa-microphone,
  //.ptz-zoomout {
  //  cursor: pointer;
  //  &.readonly {
  //    cursor: auto;
  //  }
  //}
}

</style>
